Tensorflow-python:圖片分類 Sequential model:
Sequential model 是一種常用的深度學習模型結構,尤其在處理序列數據時表現優異。這種模型按順序構建層次結構,每一層的輸出直接作為下一層的輸入,這樣的特性使得它特別適合處理時間序列或文本數據。Sequential model 的典型應用包括語言模型、語音識別和時間序列預測等。
Tensorflow-python:圖片分類-2-變形應用 :
在原本的圖片分類中,只能將圖片分類到特定的指定類別中,而這次的變形應用主要想法是將相似度做一個分界然後做成可以擴充的圖片分類器。
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential
import pathlib
import glob
import matplotlib.pyplot as plt
import numpy as np
import os
import PIL
import time
import PIL.Image as Image
import joblib
import os
import cv2 as cv
os.environ['TF_XLA_FLAGS'] = '--tf_xla_enable_xla_devices'
data_dir = pathlib.Path("/content/drive/MyDrive/train_data")
i = 0
batch_size = 32
img_height = 180
img_width = 180
train_ds = tf.keras.utils.image_dataset_from_directory(
data_dir,
validation_split=0.2,
subset="training",
seed=3,
image_size=(img_height, img_width),
batch_size=batch_size)
val_ds = tf.keras.utils.image_dataset_from_directory(
data_dir,
validation_split=0.8,
subset="validation",
seed=3,
image_size=(img_height, img_width),
batch_size=batch_size)
class_names = train_ds.class_names
print(class_names)
os.chdir('/content/drive/MyDrive/')
AUTOTUNE = tf.data.AUTOTUNE
num_classes = len(class_names)
data_augmentation = keras.Sequential(
[
layers.RandomFlip("horizontal",
input_shape=(img_height,
img_width,
3)),
layers.RandomRotation(0.1),
layers.RandomZoom(0.1),
]
)
model = tf.keras.Sequential([
data_augmentation,
tf.keras.layers.Conv2D(64, 3, activation='relu',input_shape=(1,img_height, img_width, 3)),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Conv2D(32, 3, activation='relu'),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Conv2D(16, 3, activation='relu'),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Conv2D(8, 3, activation='relu'),
tf.keras.layers.MaxPooling2D(),
layers.Dropout(0.2),
tf.keras.layers.Flatten(
),
tf.keras.layers.Dense(8, activation='relu'),
tf.keras.layers.Dense(num_classes+i)
])
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
#model = joblib.load('../h5/model.h5')
history = model.fit(
train_ds,
validation_data=val_ds,
epochs=5
)
model.summary()
joblib.dump(model,'/content/drive/MyDrive/model/model_1.h5')
img = Image.open('/content/drive/MyDrive/test_data/2.jpg').convert('RGB')
img = img.resize((img_height, img_width))
img_array = tf.keras.utils.img_to_array(img)
img_array = tf.expand_dims(img_array, 0)
predictions = model.predict(img_array)
score = tf.nn.softmax(predictions[0])
print("This image most likely belongs to {} with a {:.2f} percent confidence.".format(class_names[np.argmax(score)], 100 * np.max(score)))
#os.rmdir('/content/drive/MyDrive/train_data/'+str(i))
while(1):
if(100 * np.max(score) <70):
os.mkdir('/content/drive/MyDrive/train_data/'+str(i))
img.save('train_data/'+str(i)+'/'+str(i)+'.jpg')
i = i+1
model = tf.keras.Sequential([
data_augmentation,
tf.keras.layers.Conv2D(64, 3, activation='relu',input_shape=(1,img_height, img_width, 3)),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Conv2D(32, 3, activation='relu'),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Conv2D(16, 3, activation='relu'),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Conv2D(8, 3, activation='relu'),
tf.keras.layers.MaxPooling2D(),
layers.Dropout(0.2),
tf.keras.layers.Flatten(
),
tf.keras.layers.Dense(8, activation='relu'),
tf.keras.layers.Dense(num_classes+i)
])
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
#model = joblib.load('../h5/model.h5')
history = model.fit(
train_ds,
validation_data=val_ds,
epochs=15
)
model.summary()
joblib.dump(model,'/content/drive/MyDrive/model/model_1.h5')
img = Image.open('/content/drive/MyDrive/test_data/2.jpg').convert('RGB')
img = img.resize((img_height, img_width))
img_array = tf.keras.utils.img_to_array(img)
img_array = tf.expand_dims(img_array, 0)
predictions = model.predict(img_array)
score = tf.nn.softmax(predictions[0])
print("This image most likely belongs to {} with a {:.2f} percent confidence.".format(class_names[np.argmax(score)], 100 * np.max(score)))
else:
break
這篇文章主要提供一個想法,可能無法完全實現。
文章主題一覽:
粗體字為額外更新的文章。